package cn.ifrank.edu.case16110100410

import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.*
import androidx.viewpager.widget.ViewPager
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), TestFragment.OnFragmentInteractionListener {

    private val mFragmentList:MutableList<Fragment> = arrayListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        bottomNav.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.menu_home -> viewPager.currentItem = 0
                R.id.menu_page2 -> viewPager.currentItem = 1
                R.id.menu_page3 -> viewPager.currentItem = 2
                else -> return@setOnNavigationItemSelectedListener false
            }
            return@setOnNavigationItemSelectedListener true
        }

        mFragmentList.add(TestFragment.newInstance("这是主页"))
        mFragmentList.add(TestFragment.newInstance("这是第二页"))
        mFragmentList.add(TestFragment.newInstance("这是第三页"))

        viewPager.adapter = TestPagerAdapter(supportFragmentManager)
        viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageSelected(position: Int) {
                when (position) {
                    0 -> bottomNav.selectedItemId = R.id.menu_home
                    1 -> bottomNav.selectedItemId = R.id.menu_page2
                    2 -> bottomNav.selectedItemId = R.id.menu_page3
                }
            }
            override fun onPageScrollStateChanged(state: Int) {
            }
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

        })

    }

    private inner class TestPagerAdapter(fm: FragmentManager?) : FragmentPagerAdapter(fm) {
        override fun getItem(position: Int): Fragment {
            return mFragmentList[position]
        }

        override fun getCount(): Int {
            return mFragmentList.size
        }

    }

    override fun onFragmentInteraction(uri: Uri) {
    }



}

